﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using SHomeWorkshop.LunarPresentation.Commands;

namespace SHomeWorkshop.LunarPresentation
{
    public class ImageTreeViewItem : System.Windows.Controls.TreeViewItem
    {
        public ImageTreeViewItem(string imageDirectoryFullPath)
        {
            if (Directory.Exists(imageDirectoryFullPath) == false) return;

            string[] imgFileFullPaths = System.IO.Directory.GetFiles(imageDirectoryFullPath);

            #region 树型框项目的头部。
            int index = imageDirectoryFullPath.LastIndexOf('\\');
            string shortname = null;
            if (index >= 0)
            {
                shortname = imageDirectoryFullPath.Substring(index + 1);
            }
            else
            {
                shortname = imageDirectoryFullPath;
            }

            this.Header = shortname;

            //this.Foreground = Brushes.White;
            //this.Background = Brushes.Transparent;

            #endregion

            if (imgFileFullPaths.Length <= 0)
            {
                this.AddChild(new TreeViewItem().Header = "此类别无图像...");
            }
            else
            {
                //将所有项目都添加到树型框的内部。
                WrapPanel wpanel = new WrapPanel();
                wpanel.Width = 240;

                foreach (string filepath in imgFileFullPaths)
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.UriSource = new Uri(filepath, UriKind.Absolute);
                    bitmapImage.EndInit();

                    ImgButton imgButton = new ImgButton(filepath);
                    imgButton.MainImage.Source = bitmapImage;
                    imgButton.MainImage.Width = bitmapImage.PixelWidth;
                    imgButton.MainImage.Height = bitmapImage.PixelHeight;

                    imgButton.Click += new RoutedEventHandler(imgButton_Click);
                    imgButton.MouseRightButtonDown += new System.Windows.Input.MouseButtonEventHandler(imgButton_MouseRightButtonDown);
                    wpanel.Children.Add(imgButton);
                }

                TreeViewItem tvi = new TreeViewItem();
                tvi.Header = wpanel;

                this.AddChild(tvi);
            }
        }

        void imgButton_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //指定为通配式。

            if ((sender is ImgButton) == false) return;
            ImgButton button = sender as ImgButton;

            System.IO.FileInfo fileInfo = new FileInfo(button.ImgFileFullPath);

            if (fileInfo.Exists == false)
            {
                System.Windows.MessageBox.Show("文件不存在！在本程序已开始执行之后，您可能删除了如下位置的文件：\r\n" +
                    button.ImgFileFullPath, Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (fileInfo.Length <= 512000)//将图片限制在五百KB以内
            {
                System.Drawing.Image fileImg = System.Drawing.Image.FromFile(button.ImgFileFullPath);
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    try
                    {
                        if (fileInfo.Extension.ToLower() == ".png")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        else if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".jpeg")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else if (fileInfo.Extension.ToLower() == ".gif")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
                        }
                        else if (fileInfo.Extension.ToLower() == ".tiff")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff);
                        }
                        else if (fileInfo.Extension.ToLower() == ".bmp")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("不能识别的图片格式！", Globals.appName,
                                   MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;//不能识别的文件格式。
                        }

                        byte[] b = stream.GetBuffer();
                        string imgDataText = Convert.ToBase64String(b);

                        string picExXml = "<Expression Type=\"PictureBox\" Indent=\"0\"><Image>" + imgDataText + "</Image></Expression>";

                        Globals.wildcardExpressionXmlString = picExXml;
                    }
                    catch (System.Runtime.InteropServices.ExternalException ex)
                    {
                        Dialogs.LunarMsgBox.MsgBoxShow(
                            Globals.appName,
                            "此图像文件后缀名可能有误。",
                            "该图像以错误的图像格式后缀名保存！\r\n" + ex.Message,
                            ex.StackTrace, MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
            }
            else
            {
                Dialogs.LunarMsgBox.MsgBoxShow(
                    Globals.appName,
                    "图片文件太大。",
                    "为防止文档体积过分庞大，本图片框只支持文件尺寸在 500KB 以下的图片！",
                    "请将图片加工一下或另选一张图片。",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
        }

        void imgButton_Click(object sender, RoutedEventArgs e)
        {
            if (Globals.selectedEditor == null)
            {
                MessageBox.Show("当前没有打开任何编辑器！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (Globals.selectedEditor.SelectedExpression == null)
            {
                MessageBox.Show("请先选中一个公式作为插入基准位置！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if ((sender is ImgButton) == false) return;

            ImgButton button = sender as ImgButton;

            System.IO.FileInfo fileInfo = new FileInfo(button.ImgFileFullPath);

            if (fileInfo.Exists == false)
            {
                System.Windows.MessageBox.Show("文件不存在！在本程序已开始执行之后，您可能删除了如下位置的文件：\r\n" +
                    button.ImgFileFullPath, Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (fileInfo.Length <= 512000)//将图片限制在五百KB以内
            {
                System.Drawing.Image fileImg = System.Drawing.Image.FromFile(button.ImgFileFullPath);
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    try
                    {
                        if (fileInfo.Extension.ToLower() == ".png")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        else if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".jpeg")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else if (fileInfo.Extension.ToLower() == ".gif")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
                        }
                        else if (fileInfo.Extension.ToLower() == ".tiff")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff);
                        }
                        else if (fileInfo.Extension.ToLower() == ".bmp")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("不能识别的图片格式！", Globals.appName,
                                   MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;//不能识别的文件格式。
                        }

                        bool insertAtPreview = true;
                        bool isLeftCtrlDown = System.Windows.Input.Keyboard.IsKeyDown(Key.LeftCtrl);
                        bool isRightCtrlDown = System.Windows.Input.Keyboard.IsKeyDown(Key.RightCtrl);
                        insertAtPreview = !(isLeftCtrlDown || isRightCtrlDown);

                        ModifingItem mi = new ModifingItem();

                        Expressions.PictureBox pictureBox = Command.InsertExpression(TypeOfExpression.PictureBox,
                             LunarPresentation.Properties.Resources.PictureBox, !insertAtPreview, mi) as Expressions.PictureBox;

                        if (pictureBox == null)
                        {
                            //不必重复提示。
                            //System.Windows.MessageBox.Show("发生意外，未能在指定位置插入新图片框！", Globals.appName,
                            //   MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }

                        //调用的这个方法在mi不为空时，不会自动添加下面这个Action。
                        Action insertEx = new Action(pictureBox.ExID, pictureBox.ParentPanel.BasePanel.Children.IndexOf(pictureBox),
                            pictureBox.GetType().Name, "InsertExpression", null, pictureBox.XmlData.OuterXml, ActionType.Insert,
                            pictureBox.ParentPanel.ExID);
                        mi.Add(insertEx);

                        byte[] b = stream.GetBuffer();
                        string imgDataText = Convert.ToBase64String(b);

                        XmlNode imgNode = pictureBox.XmlData.SelectSingleNode("Image");

                        //pictureBox.XmlData.SetAttribute("Width", fileImg.Width.ToString());
                        //pictureBox.XmlData.SetAttribute("Height", fileImg.Height.ToString());

                        pictureBox.Img.Width = fileImg.Width;
                        pictureBox.Img.Height = fileImg.Height;

                        if (imgNode == null)
                        {
                            imgNode = pictureBox.XmlData.AppendChild(
                                pictureBox.XmlData.OwnerDocument.CreateNode(XmlNodeType.Text, "Image", string.Empty));
                        }
                        imgNode.InnerText = imgDataText;

                        pictureBox.Img.Source = new BitmapImage(new Uri(button.ImgFileFullPath));

                        Action action = new Action(pictureBox.ExID, -1, pictureBox.GetType().Name,
                            "ImageBase64", null, imgDataText);
                        mi.Add(action);

                        pictureBox.Editor.IsModified = true;
                    }
                    catch (System.Runtime.InteropServices.ExternalException ex)
                    {
                        Dialogs.LunarMsgBox.MsgBoxShow(
                           Globals.appName,
                           "此图像文件后缀名可能有误。",
                           "该图像以错误的图像格式后缀名保存！\r\n" + ex.Message,
                           ex.StackTrace, MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            else
            {
                Dialogs.LunarMsgBox.MsgBoxShow(
                    Globals.appName,
                    "图片文件太大。",
                    "为防止文档体积过分庞大，本图片框只支持文件尺寸在 500KB 以下的图片！",
                    "请将图片加工一下或另选一张图片。",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
        }
    }

    public class ImgButton : Button
    {
        public string ImgFileFullPath { get; set; }

        public Image MainImage { get; set; }

        public ImgButton(string imgFileFullPath)
        {
            Focusable = false;
            Background = Brushes.Black;
            ImgFileFullPath = imgFileFullPath;
            MainImage = new Image();
            Content = MainImage;
            TextBlock tb = new TextBlock() { FontFamily = Globals.defaultFontFamily };

            int index = imgFileFullPath.LastIndexOf('\\');
            string shortname = "";
            if (index >= 0)
            {
                shortname = imgFileFullPath.Substring(index + 1);
            }

            if (shortname != null)
            {
                tb.Text = shortname + "\r\n══════════\r\n左击在前侧插入图片框\r\n按Ctrl左击在后侧插入\r\n──────────\r\n右击则指定为通配式";
            }
            else
            {
                tb.Text = "左击插入为图片框\r\n右击指定为通配式";
            }

            ToolTip = tb;
        }
    }
}
